package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.enums.StatusEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysMember;
import com.ruoyi.system.domain.SysOrder;
import com.ruoyi.system.domain.vo.AgentVo;
import com.ruoyi.system.domain.vo.MemberVo;
import com.ruoyi.system.domain.vo.OrderVo;
import com.ruoyi.system.mapper.SysMemberMapper;
import com.ruoyi.system.mapper.SysOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysAgentMapper;
import com.ruoyi.system.domain.SysAgent;
import com.ruoyi.system.service.ISysAgentService;
import com.ruoyi.common.core.text.Convert;

/**
 * 代理商Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-08
 */
@Service
public class SysAgentServiceImpl implements ISysAgentService 
{
    @Autowired
    private SysAgentMapper sysAgentMapper;

    @Autowired
    private SysMemberMapper memberMapper;

    @Autowired
    private SysOrderMapper orderMapper;
    /**
     * 查询代理商
     * 
     * @param id 代理商主键
     * @return 代理商
     */
    @Override
    public SysAgent selectSysAgentById(Long id)
    {
        return sysAgentMapper.selectSysAgentById(id);
    }

    /**
     * 查询代理商列表
     * 
     * @param sysAgent 代理商
     * @return 代理商
     */
    @Override
    public List<SysAgent> selectSysAgentList(SysAgent sysAgent)
    {
        sysAgent.setStatus(StatusEnum.ENABLE.getCode());
        return sysAgentMapper.selectSysAgentList(sysAgent);
    }

    @Override
    public List<AgentVo> selectAgentList(SysAgent sysAgent) {
        sysAgent.setStatus(StatusEnum.ENABLE.getCode());
        List<SysAgent> sysAgents = sysAgentMapper.selectSysAgentList(sysAgent);
        if (Objects.isNull(sysAgents) || sysAgents.isEmpty()) {
            return Collections.emptyList();
        }
        return sysAgents.stream().map(agent -> {
            AgentVo agentVo = new AgentVo();
            agentVo.setId(agent.getId());
            agentVo.setName(agent.getName());
            agentVo.setMobile(agent.getMobile());
            agentVo.setWechatId(agent.getWechatId());
            agentVo.setNickName(agent.getNickName());
            agentVo.setOpenId(agent.getOpenId());
            agentVo.setAvatar(agent.getAvatar());
            agentVo.setSuperiorId(agent.getSuperiorId());
            if (Objects.nonNull(agent.getSuperiorId())) {
                SysAgent superiorAgent = sysAgentMapper.selectSysAgentById(agent.getSuperiorId());
                if (superiorAgent != null) {
                    agentVo.setSuperiorName(superiorAgent.getName());
                }
            }

            LambdaQueryWrapper<SysAgent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysAgent::getSuperiorId, agent.getId()).eq(SysAgent::getStatus, StatusEnum.ENABLE.getCode());
            List<SysAgent> childList = sysAgentMapper.selectList(queryWrapper);
            agentVo.setChildCount(childList.size());
            agentVo.setChildren(childList.stream().map(child -> {
                AgentVo childVo = new AgentVo();
                childVo.setId(child.getId());
                childVo.setName(child.getName());
                childVo.setMobile(child.getMobile());
                childVo.setWechatId(child.getWechatId());
                childVo.setNickName(child.getNickName());
                childVo.setOpenId(child.getOpenId());
                childVo.setAvatar(child.getAvatar());
                childVo.setSuperiorId(child.getSuperiorId());
                childVo.setSuperiorName(agent.getName());
                return childVo;
            }).collect(Collectors.toList()));

            LambdaQueryWrapper<SysMember> memberQueryWrapper = new LambdaQueryWrapper<>();
            memberQueryWrapper.eq(SysMember::getLevel1Id, agent.getId()).or(w -> w.eq(SysMember::getLevel2Id, agent.getId()));
            List<SysMember> memberList = memberMapper.selectList(memberQueryWrapper);
            agentVo.setMemberCount(memberList.size());
            agentVo.setMemberList(memberList.stream().map(member -> {
                MemberVo memberVo = new MemberVo();
                memberVo.setId(member.getId());
                memberVo.setName(member.getName());
                memberVo.setMobile(member.getMobile());
                memberVo.setWechatId(member.getWechatId());
                memberVo.setNickName(member.getNickName());
                memberVo.setOpenId(member.getOpenId());
                memberVo.setStudentFlag(member.getStudentFlag());
                return memberVo;
            }).collect(Collectors.toList()));


            List<SysMember> studentMembers = memberList.stream().filter(sysMember -> sysMember.getStudentFlag() == 1).collect(Collectors.toList());
            agentVo.setStudentList(studentMembers.stream().map(member -> {
                MemberVo memberVo = new MemberVo();
                memberVo.setId(member.getId());
                memberVo.setName(member.getName());
                memberVo.setMobile(member.getMobile());
                memberVo.setWechatId(member.getWechatId());
                memberVo.setNickName(member.getNickName());
                memberVo.setOpenId(member.getOpenId());
                memberVo.setStudentFlag(member.getStudentFlag());
                return memberVo;
            }).collect(Collectors.toList()));
            agentVo.setStudentCount(studentMembers.size());

            LambdaQueryWrapper<SysOrder> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(SysOrder::getLevel1Id, agent.getId()).or( w -> w.eq(SysOrder::getLevel2Id, agent.getId())).eq(SysOrder::getDeleteFlag, StatusEnum.NORMAL.getCode());
            List<SysOrder> sysOrders = orderMapper.selectList(orderWrapper);
            agentVo.setOrderList(sysOrders.stream().map(order -> {
                OrderVo orderVo = new OrderVo();
                orderVo.setId(order.getId());
                orderVo.setOrderNo(order.getOrderNo());
                orderVo.setCourseName(order.getCourseName());
                orderVo.setDealTime(order.getDealTime());
                orderVo.setRefundAmount(order.getRefundAmount());
                orderVo.setOrderSource(order.getOrderSource());
                orderVo.setCourseNo(order.getCourseNo());
                orderVo.setName(order.getName());
                orderVo.setMobile(order.getMobile());
                orderVo.setWechatId(order.getWechatId());
                orderVo.setNickName(order.getNickName());
                orderVo.setPayAmount(order.getPayAmount());
                orderVo.setUserStatus(order.getUserStatus());
                orderVo.setPayStatus(order.getPayStatus());
                orderVo.setCreateTime(order.getCreateTime());
                orderVo.setRefundStatus(order.getRefundStatus());
                orderVo.setLevel2Id(order.getLevel2Id());
                orderVo.setLevel1Id(order.getLevel1Id());
                orderVo.setOpenId(order.getOpenId());
                return orderVo;
            }).collect(Collectors.toList()));
            agentVo.setTotalAmount(sysOrders.stream().map(order -> order.getPayAmount()).reduce(BigDecimal.ZERO, BigDecimal::add));
            return agentVo;
        }).collect(Collectors.toList());
    }

    /**
     * 新增代理商
     * 
     * @param sysAgent 代理商
     * @return 结果
     */
    @Override
    public int insertSysAgent(SysAgent sysAgent)
    {
        LambdaQueryWrapper<SysAgent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysAgent::getMobile, sysAgent.getMobile()).eq(SysAgent::getName, sysAgent.getName());
        Long count = sysAgentMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ServiceException("用户名和手机号已存在");
        }
        //二级代理
        if (sysAgent.getLevel() == 2 && sysAgent.getSuperiorId() == null) {
            throw new ServiceException("请选择上级代理");
        }
        //判断是否是一级代理
        if (Objects.nonNull(sysAgent.getSuperiorId())){
            SysAgent proxyAgent = sysAgentMapper.selectSysAgentById(sysAgent.getSuperiorId());
            if (proxyAgent == null) {
                throw new ServiceException("上级代理不存在");
            }
            if (proxyAgent.getLevel() != 1) {
                throw new ServiceException("上级代理不是一级代理");
            }
        }
        sysAgent.setCreateTime(DateUtils.getNowDate());
        return sysAgentMapper.insertSysAgent(sysAgent);
    }

    /**
     * 修改代理商
     * 
     * @param sysAgent 代理商
     * @return 结果
     */
    @Override
    public int updateSysAgent(SysAgent sysAgent)
    {
        SysAgent old = sysAgentMapper.selectSysAgentById(sysAgent.getId());
        if (old == null) {
            throw new ServiceException("代理商不存在");
        }
        if (sysAgent.getLevel() == 2 && sysAgent.getSuperiorId() == null) {
            throw new ServiceException("请选择上级代理");
        }
        //判断是否是一级代理
        if (Objects.nonNull(sysAgent.getSuperiorId())){
            SysAgent proxyAgent = sysAgentMapper.selectSysAgentById(sysAgent.getSuperiorId());
            if (proxyAgent == null) {
                throw new ServiceException("上级代理不存在");
            }
            if (proxyAgent.getLevel() != 1) {
                throw new ServiceException("上级代理不是一级代理");
            }
        }
        if (!old.getMobile().equals(sysAgent.getMobile()) || !old.getName().equals(sysAgent.getName())) {
            LambdaQueryWrapper<SysAgent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysAgent::getMobile, sysAgent.getMobile()).eq(SysAgent::getName, sysAgent.getName()).ne(SysAgent::getId, sysAgent.getId());
            Long count = sysAgentMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new ServiceException("用户名和手机号已存在");
            }
        }
        sysAgent.setUpdateTime(DateUtils.getNowDate());
        return sysAgentMapper.updateSysAgent(sysAgent);
    }

    /**
     * 批量删除代理商
     * 
     * @param ids 需要删除的代理商主键
     * @return 结果
     */
    @Override
    public int deleteSysAgentByIds(String ids)
    {
        return sysAgentMapper.deleteSysAgentByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除代理商信息
     * 
     * @param id 代理商主键
     * @return 结果
     */
    @Override
    public int deleteSysAgentById(Long id)
    {
        return sysAgentMapper.deleteSysAgentById(id);
    }

    @Override
    public List<SysAgent> level2List(Long agentId) {

        LambdaQueryWrapper<SysAgent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysAgent::getSuperiorId, agentId);
        return sysAgentMapper.selectList(queryWrapper);
    }
}
